<template>
  <view class="cu-bar bg-white margin-top">
    <view class="action" v-if="title">
      <text v-if="required" class="text-red">*</text>{{ title }}
    </view>
  </view>
  <view class="cu-form-group">
    <view class="grid col-4 grid-square flex-sub">
      <view class="bg-img" v-for="(item,index) in imgList" :key="index" @tap="previewImage(item)" :data-url="imgList[index]">
        <image :src="item.startsWith('http') || item.startsWith('wxfile')?item:`${BASE_URL}/browse?picfilename=${item}`" mode="aspectFill"></image>
        <view class="cu-tag bg-red" @tap.stop="delImage" :data-index="index" v-if="!disabled">
          <text class='cuIcon-close'></text>
        </view>
      </view>
      <view class="solids" @tap="chooseImg(compress)" v-if="imgList.length === 0 && !disabled">
        <text class='cuIcon-cameraadd'></text>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import {useUpload} from "./useUpload";
import {usePreview} from "../../utils/usePreview";
import {inject, watch, watchEffect, watchPostEffect} from "vue";

interface CuUploaderProps {
  title?: string
  required?: boolean
  name?: string
  disabled?: boolean
  compress?: boolean
}
const props = withDefaults(defineProps<CuUploaderProps>(), {
  required: false,
  disabled: false,
  compress: false,
})

const fields = inject<any>('fields')
const validate = inject<any>('validate')

const {imgList, upload, delImage, chooseImg,doDelImg,delList} = useUpload()

const {previewImage} = usePreview()

const BASE_URL = import.meta.env.VITE_PIC_URL

defineExpose({
  upload,
  delList,
  doDelImg
})

watchPostEffect(() => {
  if (props.name){

    if (fields[props.name]){
      imgList[0] = fields[props.name]
    }

    if (props.required){
      validate[props.name] = imgList.length > 0
    }
  }

})

watch(() => imgList.length,(len) => {
  if (props.name){
    fields[props.name] = len > 0 ? imgList[0] : ''
  }
})

</script>

<style scoped>

</style>
